// app.js
App({
  fetch:require('./utils/fetch.js'),
  onLaunch() {
    this.fetch('/app/checkToken',{
        token: wx.getStorageSync('token')
    },'GET').then(data =>{
      console.log('checkToken校验token返回：',data);
      // let isLogin = data.data.isLogin
      if(data.data && data.data.isLogin){
        this.onUserLoginReady()
      }else{
        this.login({
          success:()=>{
            this.onUserLoginReady()
          },
          fail:()=>{
            this.onLaunch
          }
        })
      }
    })

    
  },


login:function(options){
// 登录
wx.login({
  success: res => {
    // 发送 res.code 到后台换取 openId, sessionKey, unionId

    this.fetch('/app/wxLogin',{
        code:res.code,
        appid:'wxb567926dfb4e7700',
        secret:'db4f699204939944c7336ffd22eac9fd',
    },'POST').then(data => {
        console.log('登录接口返回：',data);
        if(data && data.code == '200'){
          let token = data.data.result.token
          let openID = data.data.result.openID
          wx.setStorageSync('token', token)
          console.log(token)
          wx.setStorageSync('openID', openID)
          
        options.success()
        }else{
          options.fail()
        }
    })

  }
})
},

userLoginReady:false,
userLoginReadyCallback:null,
onUserLoginReady:function(){
  if(this.userLoginReadyCallback){
    this.userLoginReadyCallback()
  }
    this.userLoginReady = true
},

  globalData: {
    userInfo: null
  }
})
